const path = require('path');
const { app, BrowserWindow, ipcMain } = require('electron');
var puppeteer = require('puppeteer');
const {onSearch, onStart} =  require('./server');

// 存放全局浏览器实例
let BROWSER = null;

const creatBrowser = async (name) => {
  // const browser = await puppeteer.launch({
  //   headless: false // 关闭无头模式
  // });
  const browser = await puppeteer.launch();
  return browser;
}

async function createWindow () {
  const win = new BrowserWindow({
    width: 1080,
    height: 800,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    }
  });

  
  win.loadFile('index.html');
  
  if (!BROWSER) {
    BROWSER = await creatBrowser();
  }
  
  ipcMain.handle('page:on-search', async (event, name) => {
    if (!name) {
      return []
    }
    if (!BROWSER) {
      BROWSER = await creatBrowser();
    }
    // console.log('您正在搜索人名：' + name);
    const list = await onSearch(name, BROWSER)
    return list;
  });

  ipcMain.handle('page:on-start', async (event, id) => {
    if (!BROWSER) {
      BROWSER = await creatBrowser();
    }
    const result = await onStart(id, BROWSER);
    // console.log('您正在操作ID：' + id + ' 浏览数为: ' + result.count);
    return result;
  });
}

async function start() {
  app.on('window-all-closed', async function () {
    if (process.platform !== 'darwin') {
      if (BROWSER) {
        await BROWSER.close();
      }
      app.quit();
    }
  })
  app.whenReady().then(() => {
    createWindow()
  
    app.on('activate', function () {
      if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
  })
}

start()

